package www.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Controller
@RequestMapping("/vul")
public class VulController {

    private static final Set<String> whiteDomains = new HashSet<>(Arrays.asList(
            ".a.com"
    ));

    @GetMapping
    public String vul(@RequestParam(name = "url") String url, HttpServletResponse response) throws IOException {
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
        UriComponents uriComponents2 = UriComponentsBuilder.fromHttpUrl(url).build();
        String schema = uriComponents.getScheme();
        String host = uriComponents.getHost();
        String path = uriComponents.getPath();

        System.out.printf("url:%s\n", url);
        System.out.printf("schema:%s\n", schema);
        System.out.printf("host:%s\n", host);
        System.out.printf("path:%s\n", path);

        boolean pass = false;
        for (String whiteDomain : whiteDomains) {
            if (host.endsWith(whiteDomain)) {
                pass = true;
                break;
            }
        }

        if (!pass) {
            return "error";
        }

        return "redirect:" + url;
    }
}